package com.gitee.mocoffee.embedzk.spring;

import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.ClassPathResource;

import com.gitee.mocoffee.embedzk.EmbedZK;
import com.google.common.base.Strings;

import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;

/**
 * @author lijia
 */
@FieldDefaults(level = AccessLevel.PRIVATE)
public class EmbedZKListener implements ApplicationListener<ApplicationPreparedEvent> {
    public static final String CONFIG_FILE = "config/application.yml";

    volatile EmbedZK embedzk;

    boolean enable;

    Integer port;

    String path;

    public EmbedZKListener() {
        YamlPropertiesFactoryBean y = new YamlPropertiesFactoryBean();
        y.setResources(new ClassPathResource(CONFIG_FILE));
        y.afterPropertiesSet();
        Properties conf = y.getObject();
        String enableStr = conf.getProperty("app.embedzk.enable");
        if (!Strings.isNullOrEmpty(enableStr))
            enable = Boolean.parseBoolean(enableStr);

        if (enable) {
            String portStr = conf.getProperty("app.embedzk.port");
            if (!Strings.isNullOrEmpty(portStr))
                port = Integer.parseInt(portStr);

            path = conf.getProperty("app.embedzk.path");
        }
    }

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        if (enable) {
            try {
                embedzk = new EmbedZK(port, path);
                embedzk.start();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
